package org.grow.present.config;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import jakarta.servlet.Filter;
import org.grow.present.interceptor.AuthInterceptor;
import org.grow.present.properties.CommonProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: xwg
 * @CreateDate: 2023/9/20
 */

@Configuration
@OpenAPIDefinition(security = @SecurityRequirement(name = "BearerJwt"))
@SecurityScheme(
        name = "BearerJwt",
        type = SecuritySchemeType.HTTP,
        bearerFormat = "JWT",
        scheme = "bearer"
)
public class MvcConfig implements WebMvcConfigurer {

    @Autowired
    private AuthInterceptor authInterceptor;
    @Autowired
    private CommonProperties commonProperties;
    Logger logger = LoggerFactory.getLogger(MvcConfig.class);
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        ArrayList<String> all  = new ArrayList<>();
        all.add("/**/swagger*/**");
        all.add("/**/v3/**");
        all.add("/**/jwt/*");
        all.add("/**/wx/login");
        all.add("/**/error");
        all.add("/**/favicon*/**");
        all.addAll(commonProperties.getNoAuthResources());
        logger.info("no authentication can access : "+all);
        registry.addInterceptor(authInterceptor)
                .order(1000)
                .excludePathPatterns(all);
    }
    @Value("${present.common.image-location}")
    private String location;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        file:前缀 表示文件系统  classpath：前缀 表示工程系统
        String locationex = null;
        if (location.endsWith(File.separator)){
            locationex = location;
        }else {
            locationex = location+File.separator;
        }
        registry.addResourceHandler("/static/**")
                .addResourceLocations("file:"+locationex)
                .setCachePeriod(5);
    }

    @Bean
    public FilterRegistrationBean<Filter> corsBean(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600l);
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.setAllowedMethods
                (Stream.of("POST","GET","DELETE","PUT","OPTIONS")
                        .collect(Collectors.toList()));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);
        CorsFilter corsFilter = new CorsFilter(source);
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(corsFilter);
        bean.setOrder(-1000);
        return bean;
    }
}
